#include <Charliplexing.h>
#include <avr/pgmspace.h>  

const int cols = 9;
const int rows = 14;
int bcount = 0;
unsigned int intMap[cols];
int grid[cols][rows];
//boolean waitForProcessing = true;
enum state {
  RECEIVING,
  WAITING
};

state aState = WAITING;


void setup() {
  LedSign::Init();  //Initializes the screen
  Serial.begin(9600);

}

void loop() {
  switch (aState)  {
  case WAITING:
    while(Serial.available() <= 0)  {
      Serial.print('?');
      delay(10);
    }
    aState = RECEIVING;
    break;
  case RECEIVING:
    if(Serial.available()>0)  {
      byte myByte = Serial.read();
      while(Serial.available() <=0)  {  // wait for second byte
        continue;
      }
      intMap[bcount] = (myByte<<8)|(Serial.read());
      bcount++;
      if(bcount == cols)  {  // message complete
        unparseFrame();
        DisplayBitMap();
        aState = WAITING;
        bcount = 0;
      }
    }
    break;
    /*case SENDING:
     Serial.flush();
     delay(10);
     Serial.print('?');
     
     
     for(int i = 0; i<cols; i++)  {  // printing received message
     Serial.print("["+String(i)+"] ");
     Serial.println(intMap[i]);
     }
     Serial.print('!');
     
     
     aState = WAITING;
     break;
     */
  }
}


void unparseFrame()  {
  for (int i = 0; i < cols; i++)  {
    for(int j = 0; j< rows; j++)  {
      grid[i][j] = bitRead(intMap[i], j);
    }
  }
}

void DisplayBitMap()  {
  for (int i = 0; i < cols; i++)  {
    for(int j =0; j < rows; j++)  {
      if(grid[i][rows-j]==1)  {
        LedSign::Set(j,i,1);
      }
      else{
        LedSign::Set(j,i,0);
      }
    }
  }
}










